﻿#ifndef MYHELPER_H
#define MYHELPER_H

#if defined(_MSC_VER) && (_MSC_VER >= 1600)
# pragma execution_character_set("utf-8")
#endif

#include <QtCore>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QSettings>

class MyHelper: public QObject
{

public:

    //设置为开机启动
    static void AutoRunWithSystem(bool IsAutoRun, QString AppName, QString AppPath)
    {
        QSettings *reg = new QSettings(
            "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
            QSettings::NativeFormat);

        if (IsAutoRun) {
            reg->setValue(AppName, AppPath);
        } else {
            reg->setValue(AppName, "");
        }
    }

    //判断是否是IP地址
    static bool IsIP(QString IP)
    {
        QRegExp RegExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
        return RegExp.exactMatch(IP);
    }

    //延时
    static void Sleep(int sec)
    {
        QTime dieTime = QTime::currentTime().addMSecs(sec);
        while ( QTime::currentTime() < dieTime ) {
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
        }
    }

    static QString mkMutiDir(const QString path)
    {
        QDir dir(path);
        if (dir.exists(path)){
            return path;
        }
        QString parentDir = mkMutiDir(path.mid(0,path.lastIndexOf('/')));
        QString dirname = path.mid(path.lastIndexOf('/') + 1);
        QDir parentPath(parentDir);
        if ( !dirname.isEmpty() )
            parentPath.mkpath(dirname);

        return parentDir + "/" + dirname;
    }

    static QString GetFilePath(const QString path)
    {
        qDebug()<<"app's address"<<qApp->applicationDirPath();
        QFileInfo fileInfo(qApp->applicationDirPath() + "/" + path);
        MyHelper::mkMutiDir(fileInfo.path());
        return qApp->applicationDirPath() + "/" + path;
    }

    /** 唯一ID*/
    static QString GetUUID(){
        QUuid uuid = QUuid::createUuid();
        uint num = uuid.data1/2;
        QString id = QString::number(num);

//        QString id = QString("%1%2")
//                .arg(QDateTime::currentDateTime().toMSecsSinceEpoch())
//                .arg(qrand()%999, 3, 10, QLatin1Char('0'));
//        QThread::msleep(1);
        return id;
    }

    /** 获得当前日期时间*/
    static QString GetDateTime(){
        return QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    }

    /** 获得当前日期*/
    static QString GetDate(){
        return QDate::currentDate().toString("yyyy-MM-dd");
    }
    /** 获得时间*/
    static QString GetTime(){
        return QTime::currentTime().toString("HH:mm:ss");
    }

    static void SetMoveToThread(QObject *object){

        QThread *thread = new QThread();
        object->moveToThread(thread);

        connect(thread,SIGNAL(started()),object,SLOT(Start()));
        connect(thread,SIGNAL(finished()),object,SLOT(Stop()));
        connect(object,SIGNAL(Finished()),thread,SLOT(quit()));

        thread->start();
    }
    static QString DoubToString(double val, int prec=2){
        QRegExp rx;
        rx.setPattern("(\\.){0,1}0+$");
        QString str = QString::number(val, 'f', prec).replace(rx,"");
        return str;
    }

    static QString ToHexString(QByteArray dataArray){
        QString datastr;
        for(int i=0; i<dataArray.size(); i++){
            datastr += QString("%1").arg(dataArray.at(i)&0xFF,2,16,QLatin1Char('0')).toUpper() + QString(" ");
        }
        return datastr;
    }

    static QString ToBinaryString(QByteArray dataArray){
        QString datastr;
        for(int i=0; i<dataArray.size(); i++){
            datastr += QString("%1").arg(dataArray.at(i)&0xFF,8,2,QLatin1Char('0'));
        }
        return datastr;
    }

    /** 删除目标目*/
    static void delDir(QString path){
        if(path.isEmpty()) return;

        QDir dir(path);
        dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);

        foreach(QFileInfo fileInfo, dir.entryInfoList()){
            if(fileInfo.isFile()){
                if(!fileInfo.isWritable()) {
                    QFile file(fileInfo.absoluteFilePath());
                    file.setPermissions(QFile::WriteOwner);
                }

                fileInfo.dir().remove(fileInfo.fileName());
            }else if(fileInfo.isDir()){
                delDir(fileInfo.absoluteFilePath());
            }
        }
        dir.rmpath(dir.absolutePath());
    }

    /** 删除文件*/
    static void delFile(QString filePath){
        if(filePath.isEmpty()) return;

        QFileInfo fileInfo(filePath);
        if(fileInfo.isFile()){
            if(!fileInfo.isWritable()) {
                QFile file(fileInfo.absoluteFilePath());
                file.setPermissions(QFile::WriteOwner);
            }
            fileInfo.dir().remove(fileInfo.fileName());
        }
    }


    /** 波段  0-短波 1-中波 2-调频*/
    static QString GetBandText(int band){
        QString text = "";
        if(band == 1){
            text = "中波";
        }else if(band == 0){
            text = "短波";
        }else if(band == 2){
            text = "调频";
        }
        return text;
    }

    /** 波段  0-短波 1-中波 2-调频*/
    static int GetBand(int freq){
        int band = 1;
        if(0 <= freq && freq <= 1602){   //中波 9k   535kHz - 1605kHz
            band = 1;
        }else if(freq <= 30000){         //短波 5k   2M - 30M
            band = 0;
        }else{                           //调频 100k 88M
            band = 2;
        }
        return band;
    }

    /** 步进 0-短波 1-中波 2-调频*/
    static int GetStep(int freq){
        int setp = 0;
        int band = GetBand(freq);

        if(band == 0){
            setp = 5;           //短波 5k
        }else if(band == 1){
            setp = 9;           //中波 9k
        }else{
            setp = 100;         //调频 100k
        }
        return setp;
    }

    /** 获得下次采集时间*/
    static QDateTime GetColiectTime(int coliectNum){

        int num = coliectNum;
        if(num <= 0) num = 3;
        if(num > 60) num = 60;

        int minute = QTime::currentTime().minute();
        int block = minute / (60/num) + 1;

        QTime time = QTime::currentTime();
        time.setHMS(time.hour(), 0, 0);

        QDateTime date = QDateTime::currentDateTime();
        date.setTime(time);
        date = date.addSecs(block * (60/num) * 60);
        return date;
    }

};

#endif // MYHELPER_H
